import {createStoreBindings} from "mobx-miniprogram-bindings"
import {store} from "../../store/store"
import http from "../../utils/request"
import toast from '@vant/weapp/toast/toast'
Page({
  data: {
    form:{
      title:"",
      category_id:-1,
      tag:"",
      content:"",
      image:""
    },
    title:"",
    content:"",
    fileList:[],
    showTag: false,//展示标签弹出层
    showCategory:false,
    Tag:{
      items:null,
      selected:[],
      max: 3,
    },
    Category:{
      items:null,
      mainActiveIndex: 0,
      activeId: -1,
      activeSection:"",
      activeCategory:"",
    },
    error:{
      title:"",
      content:"",
    }
  },
  onLoad(){
    this.storeBindings = createStoreBindings(this,{
      store,
      fields:["sectionList","categoryData"],
      actions:["updateShowSection","getSectionList","updateSection","setToastMessage"]
    })
  },
  onShow(){
    if(this.data.Tag.items==null){
      http.get({
        url:"/tag/all"
      }).then(res=>{
        this.setData({
          "Tag.items":res.data.data
        })
      })
    }
  },
  afterRead(event) {//文件上传回调
    const file = event.detail.file;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      filePath: file.path,
      name: 'file',
      url: 'http://localhost:8080/upload/uploadImg',
      header:{token:wx.getStorageSync('token')},
      success:(res)=>{
        // 上传完成需要更新 fileList
        const fileList = this.data.fileList;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
      },
      fail:(res)=>{
        console.log(res)
      }
    })
  },
  deleteImg(event){
    const fileList = this.data.fileList;
    fileList.splice(event.detail.index,1)
    this.setData({fileList})
  },
  showTagPopup() {
    this.setData({ showTag: true });
  },
  onCloseTagPopup() {
    this.setData({ showTag: false });
  },
  showCategoryPopup() {//展示板块弹出层
    if(this.data.Category.items==null){
      const items = []
      for(let i=0;i<this.data.sectionList.length;i++){
        const children = []
        for(let j=0;j<this.data.categoryData[i].length;j++){
          children.push({
            id:this.data.categoryData[i][j].category_id,
            text:this.data.categoryData[i][j].category_name,
          })
        }
        items.push({
          text:this.data.sectionList[i].section_name,
          children:children
        })
      }
      this.setData({
        Category:{
          items:items,
          mainActiveIndex:0,
          activeId:items[0].children[0].id,
          activeSection:items[0].text,
          activeCategory:items[0].children[0].text
        },
        showCategory: true
      })
    }
    else{
      this.setData({
        showCategory: true
      })
    }
  },
  onCloseCategoryPopup() {//关闭板块弹出层
    this.setData({ showCategory: false });
  },
  onClickCategoryNav({ detail = {} }) {//选择section
    this.setData({
      "Category.mainActiveIndex":detail.index || 0,
      "Category.activeSection":this.data.Category.items[detail.index].text,
      "Category.activeId":this.data.Category.items[detail.index].children[0].id,
      "Category.activeCategory":this.data.Category.items[detail.index].children[0].text
    });
  },
  onClickCategoryItem({ detail = {} }) {//选择category
    const activeId = this.data.activeId === detail.id ? null : detail.id;
    this.setData({ 
      "Category.activeId":activeId,
      "Category.activeCategory":detail.text,
      "form.category_id":activeId
    });
  },
  onClickTag(e){
    let selectTag = this.data.Tag.selectTag
    console.log(selectTag.indexOf(0))
    let index = e.target.dataset.index
    if(selectTag.indexOf(index)<0&&selectTag.length<this.data.Tag.max){
      selectTag.push(index)
      console.log(this.data.Tag.selectTag)
    }
    else if(selectTag.indexOf(index)<0&&selectTag.length>=this.data.Tag.max){
      toast.fail({
        message:"最多选择"+this.data.Tag.max+"项",
        duration:1500
      })
    }
    else{
      selectTag.splice(selectTag.indexOf(index),1)
      console.log(this.data.Tag.selectTag)
    }
  },
  onTagChange(e){
    this.setData({
      "Tag.selected": e.detail,
    });
    console.log(this.data.Tag.selected)
  },
  submit(){
    //封装数据
    let tags = ""
    let images = []
    for(let i of this.data.Tag.selected){
      tags = tags+this.data.Tag.items[i].tag_name+"/"
    }
    tags = tags.slice(0,-1)
    for(let j of this.data.fileList){
      images.push(j.url)
    }
    images = images.join(";")
    this.setData({
      form:{
        title:this.data.title,
        category_id:this.data.Category.activeId,
        tag:tags,
        content:this.data.content,
        image:images
      }
    }) 
    if(this.checkData()){
      toast.loading({
        message:"",
        duration:0,
        loadingType: 'spinner',
      })
      http.post({
        url:"/blog/addblog",
        data:this.data.form
      }).then(res=>{
        this.setToastMessage("发布成功")
        wx.navigateBack({
          delta: 1
        })
      },
      res=>{
        toast.fail({
          message:"发送失败"
        })
      })
    }
  },
  checkData(){//输入检测函数
    if(!this.data.form.title){
      this.setData({
        "error.title":"请填写标题"
      })
      return false
    }
    else{
      if(this.data.form.title.length>20){
        this.setData({
          "error.title":"标题不得多于20字"
        })
        return false
      }
      else{
        this.setData({
          "error.title":""
        })
      }
    }
    if(this.data.form.category_id<0){
      toast.fail({
        message:"请选择板块",
        duration:1500
      })
      return false
    }
    if(!this.data.form.content){
      this.setData({
        "error.content":"请填写内容"
      })
      return false
    }
    else{
      if(this.data.form.content.length>500){
        this.setData({
          "error.content":"正文不得多于500字"
        })
        return false
      }
      else{
        this.setData({
          "error.content":""
        })
      }
    }
    return true
  }
})